import Vue from "vue";
import ConfirmBox from "./index.vue";
import { getOrderCache } from "../../utils/index";
import { PayBackHandler } from "../../strategy/pay-back-handler";

/**
 * 支付确认弹框
 */
export default class ConfirmBoxDialog {
  constructor() {}

  /**
   * 根据缓存判断是否打开支付确认弹框
   * @param {*} isAutoSkip 是否自动跳转
   */
  perform({isAutoSkip = false, abortedMsg = ''}) {
    sessionStorage.setItem('abortedMsg', abortedMsg);
    const { order } = getOrderCache();

    if (order) {
      const ConfirmBoxConstructor = Vue.extend(ConfirmBox);
      const instance = new ConfirmBoxConstructor();
      instance.$mount();

      if (isAutoSkip) {
        // 自动查询订单状态然后进行跳转
        this.checkOrderState(() => instance.changeshowConfirmBox(false));
      } else {
        // 打开支付确认弹框
        instance.changeshowConfirmBox(true);
        document.body.appendChild(instance.$el);
      }
    }
  }

  /**
   * 根据缓存校验订单是否支付，然后进行相关跳转
   */
  checkOrderState(failCallBack = () => {}) {
    const { paySuccessUrl, payFailUrl, order } = getOrderCache();

    if (order) {
      new PayBackHandler(paySuccessUrl, payFailUrl, order).perform(failCallBack);
    }
  }
}
